<template>
	<view>
		<view>
			<uv-popup ref="popup" mode="bottom" round="20" @change="denglu_close_get" zIndex="999">
			<view class="d-neikuang-40" :style="gaoduStyle"></view>
				<view class="denglu" >
					<view class="denglu_2" >
						<view class="d-kuan">
							<view class=" ">
								<!--view class="title">
								    <view>登录</view>
								</view-->
								<view class="form">
									<view >
										<view class="tab">
											<view v-if="phone == 1" :class="loginType==1? 'select type1' : 'type1'" @click="loginType=1">快捷登录</view>
											<view  :class="loginType==2? 'select type2' : 'type2'" @click="loginType=2">账号登陆</view>
											<view  :class="loginType==3? 'select type2' : 'type3'" @click="loginType=3">注册</view>
										</view>
									    <view class="inputs">
										
											<view v-if="loginType==1" class="account">
												<view>+86</view> 
												<input type="number" v-model="yonghu.phone" :adjust-position="false" placeholder="手机号" />
											</view>
											<view v-if="loginType==2" class="account">
												<input type="text" v-model="yonghu.username" :adjust-position="false" placeholder=" 账号" />
											</view>
											<view v-if="loginType==1" class="vcode">
												<input type="number" v-model="yonghu.vcode" :adjust-position="false" placeholder="请输入验证码" />
												<text v-if="vcodeTime==0" style="color:#16afa8" @click="postRenzhengma">获取验证码</text>
												<text v-else style="color:#ccc">重新获取({{vcodeTime}}s)</text>
											</view>
											<view  v-if="loginType==2" class="vcode">
												<!-- #ifdef MP-WEIXIN -->
												<input type="text" password="true" v-model="yonghu.password" :adjust-position="false" placeholder="请输入密码" />
												<!-- #endif -->
												<!-- #ifndef MP-WEIXIN -->
												<input type="password" v-model="yonghu.password" :adjust-position="false" placeholder="请输入密码" />
												<!-- #endif -->
								        	</view>
											<!--账号登录-->
											<view v-if="loginType==3 && username == 1" class="vcode">
												 <input type="text" v-model="yonghu.username" :adjust-position="false"
													placeholder=" 账号" />
											</view>
											<view v-if="loginType==3 && phone == 1" class="vcode">
												<view class="d-you-10">+86</view> <input type="number" v-model="yonghu.phone" :adjust-position="false"
													placeholder="手机号" />
											</view>
											<view  v-if="loginType==3 && email == 1" class="vcode">
												<input type="text" v-model="yonghu.email" :adjust-position="false" placeholder="请输入邮箱" />
											</view>
										    <view  v-if="loginType==3" class="vcode">
													<!-- #ifdef MP-WEIXIN -->
													<input type="text" password="true" v-model="yonghu.password" :adjust-position="false" placeholder="请输入密码" />
													<!-- #endif -->
													<!-- #ifndef MP-WEIXIN -->
													<input type="password" v-model="yonghu.password" :adjust-position="false" placeholder="请输入密码" />
													<!-- #endif -->
											</view>
											<!--验证码登录-->
											<view v-if="loginType==3 && code == 1" class="vcode">
												<view class="d-you-10" >
													<!--图片认证码-->
													<image @click="getRenzhengma" :src="get_rzm" mode="aspectFill" class="erweima" style="width: 80px; height: 40px;"></image>
												</view> 
												<input type="text" v-model="yonghu.code" :adjust-position="false"
													placeholder="认证码" />
											</view>	
									    </view>
										<view v-if="loginType==1" class="button">
											<view @click="zhuce">
												立即登录
											</view>
										</view>
										<view v-if="tishi" class="tip d-xia-10" style="color: #16afa8;">
											<text>{{tishi}}</text>
										</view>
										<view v-if="loginType==2" class="button">
											<view @click="denglu_data">
												立即登录
											</view>
										</view>
										<view v-if="loginType==3" class="button">
											<view @click="zhuce_data">
												新用户注册
											</view>
										</view>
										<view v-if="loginType==1" class="tip">
											<text>未注册的手机号验证后即可完成注册</text>
										</view>
										<view v-if="loginType==1" class="pact">
											<radio :checked="pactChecked" activeBackgroundColor="#3ba662" activeBorderColor="#3ba662"
												borderColor="#3ba662" color="#fff" @click="pactChange" />
											<view>我已阅读并同意<text @click="toPact">《用户协议》</text>和<text @click="toPact">《隐私协议》</text></view>
										</view>
									</view>
									<view class="tip">
										<!-- #ifdef H5 -->
										<uv-button v-if="isWeixin" text="微信一键登录" shape="circle" icon="weixin-fill" @click="weixingongzhonghao" iconColor="#ffffff" color="linear-gradient(to right, rgb(60, 78, 194), rgb(213, 51, 186))"></uv-button>
										<!--uv-icon v-if="isWeixin" name="weixin-fill" color="#3ec755" size="28" label="微信一键登录" @click="weixingongzhonghao"></uv-icon-->
										<!-- #endif -->
										<!-- #ifdef MP-WEIXIN-->
										<uv-button text="微信一键登录" shape="circle" icon="weixin-fill"  @click="openProfilePopup" iconColor="#ffffff" color="linear-gradient(to right, rgb(60, 78, 194), rgb(213, 51, 186))"></uv-button>
										<!--uv-icon name="weixin-fill" color="#3ec755" size="28" label="微信一键登录"  @click="openProfilePopup"></uv-icon-->
										<!-- #endif -->
										<uni-popup ref="setinfo" type="dialog" >
										    <view style="padding: 12px;width: 260px;border-radius: 11px;background-color: #fff;">
										        <view @click="hidepop(false)" style="text-align: center;text-align: right;">
										            <text>X</text>
										        </view>
										        <view style="text-align: center;">
										            <text>完善信息</text>
										        </view>
										        <view>
										            <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
										                <image class="avatar" :src="avatarUrl" mode="widthFix"></image>
										            </button>
										        </view>
										        <view style="height: 30px;" @touchstart="requirePrivacyAuthorize">
										            <input
										                type="nickname"
										                @change="savename"
										                placeholder="设置昵称"
										                :focus="statefocus"
										                v-model="nickname">
										        </view>
										        <view style="margin-top: 10px;">
										            <button @click="hidepop(true)" type="primary">确定</button>
										        </view>
										    </view>
										</uni-popup>
										<!-- privacy组件未找到，暂时注释掉 v-if="isWechat()" -->
										
										<!-- <privacy  ref="privacy" type="bottom" :refuse="refuse" /> -->								</view>
								</view>

							</view>
						</view>
					</view>
					
					
				</view>
			</uv-popup>
			<!-- 新增：微信授权弹窗 -->
			<uni-popup ref="profilePopup" class="profile-popup" type="center" :mask-click="false" zIndex="3000">
			    <view style="padding: 24rpx; width: 560rpx; background-color: #ffffff;border-radius: 10px;">
			        <view style="font-size: 30rpx; font-weight: bold; margin-bottom: 20rpx;">获取微信头像与昵称</view>
			        <view style="font-size: 26rpx; color: #666; line-height: 1.6;">
			            我们将获取您的微信昵称与头像，用于完善会员资料与登录。
			        </view>
			        <view style="margin-top: 30rpx; display: flex; gap: 20rpx;">
			            <button type="primary" style="flex: 1;" @tap="requestUserProfile">授权并登录</button>
			            <button style="flex: 1;" @tap="closeProfilePopup">取消</button>
			        </view>
					<view class="d-clear"></view>
			    </view>
			</uni-popup>
			<!-- privacy组件未找到，暂时注释掉 v-if="isWechat()" -->
			
			<!-- <privacy  ref="privacy" type="bottom" :refuse="refuse" /> -->
			
			</view>
		</view>
	</template>

	<script>
		import Api from '@/utils/api.js'; 
		import { getRequest,postRequest } from '@/utils/wxRequest.js';
	export default {
	    props: {
			denglu_xianshi_weibu: {
			    type: [Number,String],
			    default: 0
			}
	    },
		data(){
				return {
					gaodu: 0, // 高度
					checkCodeTriggered: false, // 标记checkWeChatCode是否已触发
				vcodeTime: 0,
            vcodeTimer: null,
				yonghu:{
					username:'',
					phone:'',
					email:'',
					name:'',
					password:'',
					password2:'',
					vcode:''
				},
				pactChecked: false, // 协议勾选状态
				showDropdown: false,
				loginType: 1,
				xieyizhi:[], //协议值
				tishi:'', //提示
				zhucexuanxiang:[], //注册选项
				zhuceType: 1, //注册类型 1手机号 2邮箱
				email: 0, //是否注册邮箱
				username: 0, //是否注册用户名
				phone: 0, //是否注册手机号
				get_rzm: '', //获取注册认证码
				code: 0, //是否需要验证码
				isWeixin:'',//判断是否微信浏览器
				nickname:'',
				avatarUrl:'', // 用户头像URL
						defavatarUrl: '/static/images/default-avatar.png', // 默认头像URL
						statefocus: false, // 控制输入框焦点状态
						
					}
	},
	// 在组件销毁时清理定时器，避免内存泄漏
	destroyed() {
		if (this.vcodeTimer) {
			clearInterval(this.vcodeTimer);
			this.vcodeTimer = null;
		}
		// 移除窗口大小变化事件监听
		uni.offWindowResize(() => {
			this.updateHeight();
		});
	},
	mounted() {
		var duixin = this;
		let code = this.getUrlCode("code");
		//console.log("code",code);
		/*uni.showToast({
			title:`微信code=${code}`
		})*/
		if (!code) {
			// 10分钟后执行下一步
			this.denglu();
		}
		
		//this.$refs.popup.open();
		// 获取窗口高度并减去250rpx
		this.updateHeight();
		// 添加窗口大小变化事件监听
		uni.onWindowResize(() => {
			this.updateHeight();
		});
		this.zhucexiangmu();
		this.getRenzhengma();
		//this.$refs.popup.open();
		// #ifdef H5
			//console.log('进入H5条件编译块');
			// 直接使用this调用方法，避免作用域问题
			this.isWeixin = this.isWechat();
			//console.log('isWechat方法返回值:', this.isWeixin);
			if(this.isWeixin && !this.checkCodeTriggered){
				//console.log('检测到微信环境，准备检查微信code');
				this.checkWeChatCode();
				this.checkCodeTriggered = true; // 设置为已触发，防止重复调用
			} else {
				//console.log('非微信环境，不执行微信登录相关操作');
			}
	    // #endif
	},
	methods: {
		//登录
		denglu(){
			
			if(this.denglu_xianshi_weibu==1){

				this.$refs.popup.open();
			}
			

		},
		updateHeight() {
			const systemInfo = uni.getSystemInfoSync();
			// 通常1px = 2rpx，所以将窗口高度从px转换为rpx再减去450rpx
			this.gaodu = systemInfo.windowHeight * 2 - 450;
			// 样式由 computed: gaoduStyle 自动派生，无需直接赋值
		},
		denglu_close_get(e) {
			//console.log('关闭登录组件', e);
			//this.$refs.popup.close();
			this.$emit('denglu_close_get');
		},
		// 新增：弹出授权窗
		openProfilePopup() {
			// 先关闭底部登录弹窗，避免遮挡授权弹窗
			if (this.$refs.popup && this.$refs.popup.close) {
				this.$refs.popup.close();
			}
			this.$nextTick(() => {
				if (this.$refs.profilePopup && this.$refs.profilePopup.open) {
					this.$refs.profilePopup.open();
				}
			});
		},
		closeProfilePopup() {
			if (this.$refs.profilePopup) {
				this.$refs.profilePopup.close();
			}
		},
		// 新增：获取用户头像与昵称并登录
		requestUserProfile() {
			// #ifdef MP-WEIXIN
			const self = this;
			uni.getUserProfile({
				desc: '用于完善会员资料',
				success: (profileRes) => {
					const userInfo = profileRes.userInfo || {};
					uni.login({
						success: (loginRes) => {
							const jsCode = loginRes.code;
							uni.showToast({ title: '正在登录...', icon: 'loading' });
							uni.request({
								url: Api.getWwwUrl() + 's=weixin&c=member&m=xcx',
								method: 'POST',
								header: { 'Content-Type': 'application/x-www-form-urlencoded' },
								data: {
									json: JSON.stringify(userInfo),
									js_code: jsCode,
									jianceopenid: 1,
								},
								success: (response) => {
									const data = response.data;
									if (data && data.code) {
										if (data.msg === 'login') {
											const member = data.data && data.data.member;
											const uid = member && (member.uid || member.id);
											const keycode = data.data && data.data.auth;
											uni.setStorageSync('memberuid', uid);
											uni.setStorageSync('member', member);
											uni.setStorageSync('keycode', keycode);
											if (self.$store) {
												self.$store.commit('setMember', member);
												self.$store.commit('setMemberUid', uid);
												self.$store.commit('setKeycode', keycode);
											}
											uni.showToast({ title: '登录成功', icon: 'success' });
											self.$emit && self.$emit('login-success');
											self.$emit && self.$emit('denglu_close_get');
											self.closeProfilePopup();
											self.touxiang = (member && member.avatar) || (userInfo && userInfo.avatarUrl) || self.touxiang;
											self.name1 = (member && (member.name || member.username)) || (userInfo && userInfo.nickName) || self.name1;
										} else {
											uni.showModal({ showCancel: false, content: '后台微信插件中需要开启直接登录模式' });
										}
									} else {
										uni.showModal({ showCancel: false, content: (data && data.msg) || '登录失败，请稍后重试' });
									}
								},
								fail: (err) => {
									console.error('登录请求失败', err);
									uni.showToast({ icon: 'none', title: '登录请求失败' });
								}
							});
						},
						fail: (err) => {
							console.error('uni.login 失败', err);
							uni.showToast({ icon: 'none', title: '获取登录凭证失败' });
						}
					});
				},
				fail: (err) => {
					console.warn('用户拒绝授权', err);
					uni.showToast({ icon: 'none', title: '您已取消授权' });
				}
			});
			// #endif
			// #ifndef MP-WEIXIN
			uni.showToast({ icon: 'none', title: '当前环境不支持微信授权' });
			// #endif
		},
		// getVcode方法已合并到postRenzhengma中，避免重复设置定时器导致栈溢出
		// 登录认证码
		postRenzhengma(){
			var d = this;
			var phone = d.yonghu.phone; //手机号码可选
			
			// 判断 手机号不能为空
			// 添加手机号非空验证
			if(!phone) {
				uni.showToast({
					title: '请输入手机号码',
					icon: 'none'
				});
				return;
			}
		
			// 添加手机号格式验证
			if(!/^1[3-9]\d{9}$/.test(phone)) {
				uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				});
				return;
			}
			// 先清除旧的定时器（如果存在），防止重复创建导致的问题
			if (this.vcodeTimer) {
				clearInterval(this.vcodeTimer);
				this.vcodeTimer = null;
			}
			this.vcodeTime = 60
			this.vcodeTimer = setInterval(() => {
				if (this.vcodeTime > 0) {
					this.vcodeTime--
				} else {
					clearInterval(this.vcodeTimer)
					this.vcodeTimer = null
				}
			}, 1000)
				
			uni.showToast({
					title: "获取验证码",
					icon: 'none'
				})
				var datas = '&id=' + phone;
				
				
				var post_data = getRequest(Api.postRenzhengma(phone),datas);
				var res;
				post_data.then(response => {
					res = response;
					if(res.data.code) 	{
						uni.showToast({
							title: '发送成功',
							icon: 'success',
							duration: 2000
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: response.data.msg
						});
					}
				})
		},
		// 用户注册
		async zhuce(){
			try {
				var d = this;
				
				if(!d.xieyizhi || d.xieyizhi.length === 0) {
					
				    uni.showToast({
				        title: '请先同意用户协议和隐私协议',
				        icon: 'none'
				    });
				    return;
				}
		
				var username = d.yonghu.username; //账号
				var name = d.yonghu.name; //账号
				var password = d.yonghu.password; //密码
				var password2 = d.yonghu.password; //确认密码2
				var email = d.yonghu.email; //邮箱可选
				var phone = d.yonghu.phone; //手机号码可选
				var protocol = d.xieyizhi[0]; //是否同意协议
				var vcode = d.yonghu.vcode; //验证码
				//var datas = "is_ajax=1&data[password]="+password+"&data[password2]="+password2+"&is_protocol="+protocol;
				var datas = "&is_ajax=1";
				if(username){
					datas += '&data[username]=' + username;
				}
				if(phone){
					datas += '&data[phone]=' + phone;
				}
				if(email){
					datas += '&data[email]=' + email;
				}
				if(name){
					datas += '&data[name]=' + name;
				}
				if(vcode){
					datas += '&sms=' + vcode;
				}
				//postYonghuRegiste
				/*const params = {
				    is_ajax: 1,
				    is_protocol: protocol,
				    data: {
						...(name && {username: name}),
						...(username && {username: username}), // 只有username有值时才包含在data中
						...(email && {email: email}), // 只有email有值时才包含在data中
						...(phone && {phone: phone}), // 同样处理phone
					    password: password,
					    password2: password2
					},
				    
				    
				};*/
				var post_data = postRequest(Api.postYonghuLogin_sms(),datas);
				var res;
				post_data.then(response => {
					res = response;
					if(res.data.code) {
						uni.showToast({
							title: '操作成功',
							icon: 'success',
							duration: 2000
						});
						 // 保存用户信息到本地storage
						//uni.setStorageSync('userInfo', response.data.data.member.auth);
						uni.setStorageSync('memberuid', response.data.data.member && response.data.data.member.id);
						uni.setStorageSync('member', response.data.data.member);
						uni.setStorageSync('keycode', response.data.data.auth);

						this.$store.commit('setMember', response.data.data.member);
						this.$store.commit('setMemberUid', response.data.data.member.id);
						this.$store.commit('setKeycode', response.data.data.auth);
						//this.yidenglu = 1;
						//this.denglu_xianshi = this.denglu_xianshi === 0 ? 1 : 0;
						this.$emit('login-success'); // 添加这行
						this.$emit('denglu_close_get');//关闭登录窗口
						this.$refs.popup.close();
						//头像
						this.touxiang = response.data.data.member && response.data.data.member.avatar;
						//昵称
						if(!response.data.data.member && response.data.data.member.name){
							this.name1 = response.data.data.member && response.data.data.member.username;

						} else {
							//昵称
							this.name1 = response.data.data.member && response.data.data.member.name;
						}
						//关闭弹出
						//登录跳转到登录页面
						//uni.reLaunch({ url: "/pages/index/index" });
					} else {
						uni.showToast({
							icon: 'none',
							title: response.data.msg
						});
					}
				})
			} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '注册失败，请稍后重试'
				});
			}
		},
		// 用户注册
		async denglu_data(){
			try {
				var d = this;
				/*if(!d.xieyizhi || d.xieyizhi.length === 0) {
					
				    uni.showToast({
				        title: '请先同意用户协议和隐私协议',
				        icon: 'none'
				    });
				    return;
				}*/
				var username = d.yonghu.username; //账号
				var name = d.yonghu.name; //账号
				var password = d.yonghu.password; //密码
				var password2 = d.yonghu.password; //确认密码2
				var email = d.yonghu.email; //邮箱可选
				var phone = d.yonghu.phone; //手机号码可选
				var protocol = d.xieyizhi[0]; //是否同意协议
				//检查d.xieyizhi是否打勾
				var datas = "is_ajax=1&data[password]="+password+"&is_protocol="+protocol;
				if(username){
					datas += '&data[username]=' + username;
				}
				if(phone){
					datas += '&data[phone]=' + phone;
				}
				if(email){
					datas += '&data[email]=' + email;
				}
				if(name){
					datas += '&data[name]=' + name;
				}
				var post_data = postRequest(Api.postYonghuLogin(),datas);
				var res;
				post_data.then(response => {
					res = response;
					if(res.data.code) {
						uni.showToast({
							title: '操作成功',
							icon: 'success',
							duration: 2000
						});
						 // 保存用户信息到本地storage
						//uni.setStorageSync('userInfo', response.data.data.member.auth);
						uni.setStorageSync('memberuid', response.data.data.member.uid);
						uni.setStorageSync('member', response.data.data.member);
						uni.setStorageSync('keycode', response.data.data.member.auth);
						this.$store.commit('setMember', response.data.data.member);
						this.$store.commit('setMemberUid', response.data.data.member && response.data.data.member.uid);
						this.$store.commit('setKeycode', response.data.data.auth);
						//头像
						this.touxiang = response.data.data.member.avatar;
						//昵称
						if(!response.data.data.member.name){
							this.name1 = response.data.data.member.username;

						} else {
							//昵称
							this.name1 = response.data.data.member.name;
						}
						
						//this.yidenglu = 1;
						//this.denglu_xianshi = this.denglu_xianshi === 0 ? 1 : 0;
						
						this.$emit('login-success'); // 添加这行
						this.$emit('denglu_close_get');//关闭登录窗口
						this.$refs.popup.close();
						
						//关闭弹出
						//登录跳转到登录页面
						//uni.reLaunch({ url: "/pages/index/index" });
					} else {
						uni.showToast({
							icon: 'none',
							title: response.data.msg
						});
					}
				})
			} catch (error) {
				console.error(error);
				uni.showToast({
					icon: 'none',
					title: '注册失败，请稍后重试'
				});
			}
		},
		
		toPact(){
			console.log("协议");
		},
		pactChange(){
			this.pactChecked = !this.pactChecked;  // 切换勾选状态
			this.xieyizhi = this.pactChecked ? [1] : [];
		},
		exitlogin() {
			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('memberuid');
			uni.removeStorageSync('keycode');
			uni.removeStorageSync('member');
			uni.reLaunch({ url: '/pages/login/login'})
		},
		daohang_click(index){
			console.log(index);
			this.$emit('daohang_click', index);
		},
		//新用户注册
		async zhuce_data(){
			try {
				var d = this;
				var username = d.yonghu.username; //账号
				var name = d.yonghu.name; //账号
				var password = d.yonghu.password; //密码
				var password2 = d.yonghu.password; //确认密码2
				var email = d.yonghu.email; //邮箱可选
				var phone = d.yonghu.phone; //手机号码可选
				var code = d.yonghu.code; //认证码
				var protocol = d.xieyizhi[0]; //是否同意协议
				// 验证密码不能为空
				if (!password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return;
				}
				if(this.code==1 && !code){
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return;
				}
				var datas = "is_ajax=1&data[password]="+password+"&is_protocol="+protocol+'&data[password2]='+password;
					if(username){
						datas += '&data[username]=' + username;
					}
					if(phone){
						datas += '&data[phone]=' + phone;
					}
					if(email){
						datas += '&data[email]=' + email;
					}
					if(name){
						datas += '&data[name]=' + name;
					}
					if(this.code==1){
						datas += '&data[code]=' + code;
					}
					var post_data = postRequest(Api.postYonghuRegiste(),datas);
					var res;
					post_data.then(response => {
						res = response;
						if(res.data.code) {	
							uni.showToast({
								title: '注册成功',
								icon: 'success',
								duration: 2000
							});
							 // 保存用户信息到本地storage
							//uni.setStorageSync('userInfo', response.data.data.member.auth);
							uni.setStorageSync('memberuid', response.data.data && response.data.data.member && response.data.data.member.uid);
							uni.setStorageSync('member', response.data.data && response.data.data.member && response.data.data.member);
							uni.setStorageSync('keycode', response.data.data && response.data.data.member && response.data.data.member.auth);
							this.$store.commit('setMember', response.data.data && response.data.data.member);
							this.$store.commit('setMemberUid', response.data.data && response.data.data.member && response.data.data.member.uid);
							this.$store.commit('setKeycode', response.data.data && response.data.data.member && response.data.data.member.auth);
							//头像
							this.touxiang = response.data.data.member.avatar;
							//昵称
							if(!response.data.data.member.name){
								this.name1 = response.data.data.member.username;

							} else {
								//昵称
								this.name1 = response.data.data.member.name;
							}
							
							//this.yidenglu = 1;
							//this.denglu_xianshi = this.denglu_xianshi === 0 ? 1 : 0;
							this.$emit('login-success'); // 添加这行
							this.$emit('denglu_close_get');//关闭登录窗口
							this.$refs.popup.close();
							//关闭弹出
							//登录跳转到登录页面
							//uni.reLaunch({ url: "/pages/index/index" });
						} else {
							uni.showToast({
								icon: 'none',
								title: response.data.msg
							});
						}
					})
				} catch (error) {
					console.error(error);
					uni.showToast({
						icon: 'none',
						title: '注册失败，请稍后重试'
					});
				}
			
		},

		//注册项目
		zhucexiangmu(){  
				var duixin = this;
				var postYonghuzhuceRequest = getRequest(Api.postYonghuRegiste());
				postYonghuzhuceRequest.then(response => {
					if (response.data.code == 1 && response.data.data && response.data.data.register) {
					    // 正确获取注册选项数据
						duixin.zhucexuanxiang = response.data.data.register.field || [];
						// 打印注册选项数据
						//console.log('注册选项数据:', duixin.zhucexuanxiang);
						// 判断数组中是否包含'phone'元素						
						if (Array.isArray(duixin.zhucexuanxiang) && duixin.zhucexuanxiang.includes('email')) {
							duixin.loginType = 2;
							duixin.email = 1;
							//console.log('未检测到phone字段，设置loginType为2');
						} else {
							duixin.loginType = 2;
							duixin.email = 0;
						}
			
						if (Array.isArray(duixin.zhucexuanxiang) && duixin.zhucexuanxiang.includes('username')) {
							duixin.loginType = 2;
							duixin.username = 1;
							//console.log('未检测到phone字段，设置loginType为2');
						} else {
							duixin.loginType = 2;
							duixin.username = 0;
						}
						// 判断数组中是否包含'phone'元素	
						if(Array.isArray(duixin.zhucexuanxiang) && duixin.zhucexuanxiang.includes('phone')){
							duixin.loginType = 1;
							duixin.phone = 1;
							//console.log('检测到包含phone字段，设置loginType为1');
						} else {
							duixin.loginType = 2;
						    duixin.phone = 0;
						}
						// 判断数组中是否包含'code'元素	
						if(response.data.data && response.data.data.register.code){
							duixin.code = 1;
							//console.log('检测到需要验证码');
						} else {
							duixin.code = 0;
							//console.log('不需要验证码');
						}
					} else {
						//console.log('获取注册选项失败或数据格式不正确');
						duixin.zhucexuanxiang = [];
						duixin.loginType = 2;
					}
				}).catch(error => {
					//console.error('获取注册选项请求失败:', error);
					duixin.zhucexuanxiang = [];
					duixin.loginType = 2;
				});
			},

		//获取注册认证码
		getRenzhengma(){
			//console.log('获取注册认证码');
			// 添加时间戳防止缓存
			const timestamp = new Date().getTime();
			this.get_rzm = Api.getZhuceRenzhengma() + '?t=' + timestamp;
			//console.log('更新后的认证码URL:', this.get_rzm);
		},
		// 微信一键登录
		async jiancelogin(){
			try {
				var self = this;
				//console.log("到登录了");
				uni.showToast({
					title: "正在登录...",
					icon: 'loading',
					success: function () {
					}
				});
				uni.login({
				    success: function (res) {
						//console.log("到登录了login",res);
						uni.getUserInfo({
							desc: '完善会员资料',
							success: (userRes) => {
								//console.log("到登录了userRes",res);
							    uni.request({
									url: Api.getWwwUrl()+"s=weixin&c=member&m=xcx",
									data: {
										json: userRes.rawData,
										js_code: res.code,
										jianceopenid:1,
									},
									method: 'post',
									header: {
									  'Content-Type': 'application/x-www-form-urlencoded',
									},
									success: function (response) {
									  console.log(response.data);
									    if (response.data.code) {
										  if (response.data.msg == 'login') {
											  uni.setStorageSync('memberuid', response.data.data && response.data.data.member && response.data.data.member.uid);
											  uni.setStorageSync('member', response.data.data && response.data.data.member);
											  uni.setStorageSync('keycode', response.data.data && response.data.data.auth);
											  
											  self.$store.commit('setMember', response.data.data && response.data.data.member);
											  self.$store.commit('setMemberUid', response.data.data && response.data.data.member && response.data.data.member.uid);
											  self.$store.commit('setKeycode', response.data.data && response.data.data.auth);
												uni.showToast({
													title: "登录成功",
													icon: 'success',
													success: function () {
													}
												});
						
											// 跳转新页面

										  } else {
											  // 绑定账号注册
											  uni.showModal({
												  showCancel: false,
												  content: "后台微信插件中需要开启直接登录模式"
											  })
										  }
										} else if (res.data.msg == 'unoid') {
											self.showprivacy();
									    } else {
										    // 失败了
										    uni.showModal({
											    showCancel: false,
											    content: res.data.msg
										    })
									  }
									}
									});
							}
						})
					}
				});
			} catch (error) {
					console.error(error);
					uni.showToast({
						icon: 'none',
						title: '登录失败，请稍后重试'
					});
				}
		},
		refuse() {
		    // this.$refs.privacy.open()
		    uni.showToast({
		        icon: 'none',
		        title: '非常抱歉无法为您提供服务，如需服务请先同意相关协议~',
				   duration: 3000
		    });
		    return
		},
		changeFocus(e){
		      this.statefocus = e
		},
		requirePrivacyAuthorize(){
		      let _this = this
		      if (wx.getPrivacySetting) {
		          wx.getPrivacySetting({//获取是否需要弹出
		              success: res => {
		                  if (res.needAuthorization) {
		                      wx.requirePrivacyAuthorize({//该接口请求隐私协议，会自动触发上边的wx.onNeedPrivacyAuthorization
		                          success: () => {
		                              _this.statefocus = true
		                          },
		                          fail: () => {},
		                          complete: () => {}
		                      })
		                  } else {
		                      _this.statefocus = true
		                  }
		              },
		              fail: () => {},
		              complete: () => {}
		          })
		      } else {
		          _this.statefocus = true
		      }
		},
		showpop(){
		  this.$refs.setinfo.open()
		},
		hidepop(n = false){
			console.log("信息",n)
		  if (n){
			  //this.nickname.length <=0 || (this.avatarUrl.length <=0 || this.avatarUrl === this.defavatarUrl)
			  if (this.nickname.length <=0 || (this.avatarUrl.length <=0 || this.avatarUrl === this.defavatarUrl)){
				  uni.showToast({
					  title:'请选择头像 和 名称',
					  icon:"none",
					  duration:3000
				  });
				  return
			  }
			  
			  this.$refs.setinfo.close()
			  this.donelogin()
		  }else{
			  this.$refs.setinfo.close()
		  }
		},
		showprivacy(){
		   let _this = this
		   // 检查是否是微信环境
		   if(!_this.isWechat()){
		       uni.showToast({
		           title: '请在微信环境下使用',
		           icon: 'none'
		       })
		       return
		   }
		   if (wx.getPrivacySetting){
		       wx.getPrivacySetting({
		           success: (res) => {
		               console.log(res)
		               if (res.needAuthorization){
		                   // 检查privacy组件是否存在
		                   if(_this.$refs.privacy){
		                       _this.$refs.privacy.open()
		                   } else {
		                       // 组件不存在时的替代处理
		                       uni.showToast({
		                           title: '请同意隐私协议后再使用',
		                           icon: 'none'
		                       })
		                   }
		               }else{
		                   _this.xcxWxLogin()
		               }

		               // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
		           },
		           fail: () => {},
		           complete:() => {}
		       })
		   }else{
		       this.xcxWxLogin()
		   }
		},
		// #ifdef H5
		//方法：用来判断是否是微信内置的浏览器
		isWechat() {
			return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
		},
		// #endif
		// 方法: 跨端安全提取 URL 参数（支持 H5 与小程序）
		getUrlCode(name) {
			try {
				// H5: 使用 window.location.href
				if (typeof window !== 'undefined' && window.location && window.location.href) {
					const href = window.location.href;
					const m = new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(href);
					const v = m && m[1] ? m[1] : '';
					return v ? decodeURIComponent(v.replace(/\+/g, '%20')) : null;
				}
				// 小程序: 通过进入参数或当前页面 options 获取
				if (typeof uni !== 'undefined' && typeof uni.getEnterOptionsSync === 'function') {
					const enter = uni.getEnterOptionsSync() || {};
					if (enter.query && (name in enter.query)) return enter.query[name] || null;
					// 从 path 的查询字符串解析（兼容某些场景）
					const path = enter.path || '';
					if (path && path.indexOf('?') > -1) {
						const queryStr = path.split('?')[1] || '';
						const params = {};
						queryStr.split('&').forEach(kv => {
							const [k, val] = kv.split('=');
							if (k) params[k] = val ? decodeURIComponent(val.replace(/\+/g, '%20')) : '';
						});
						if (name in params) return params[name] || null;
					}
				}
				// 兜底：当前页面 options 或 Vue Router
				if (typeof getCurrentPages === 'function') {
					const pages = getCurrentPages();
					const cur = pages && pages.length ? pages[pages.length - 1] : null;
					const opt = cur && cur.options ? cur.options : null;
					if (opt && (name in opt)) return opt[name] || null;
				}
				if (this.$route && this.$route.query && (name in this.$route.query)) {
					return this.$route.query[name] || null;
				}
			} catch (e) {
				console.warn('[getUrlCode] 解析失败:', e);
			}
			return null;
		},
		// 检查浏览器地址栏中微信接口返回的code
		checkWeChatCode() {
			let code = this.getUrlCode("code");
			
			if (code) {
				// 10分钟后执行下一步
				this.getOpenidAndUserinfo(code);
			}
		},
		//把code传递给后台接口，静默登录
		getOpenidAndUserinfo(code) {
			//获取当前页面地址作为回调地址
			var duixin = this;
			let local = encodeURIComponent(window.location.href);
			//弹出登录中提示
			uni.showToast({
				title: "登录中...",
				icon: 'loading',
				duration: 2000
			});
			
			var postWeixinloginRequest = getRequest(Api.postWeixinlogin(code,local));
			//console.log('postWeixinloginRequest',postWeixinloginRequest); 
			postWeixinloginRequest.then(response => {
				if (response.data.code == 1) {
				  //console.log(response.data.data); 
				  uni.setStorageSync('memberuid', response.data.data && response.data.data.member && response.data.data.member.uid);
				  uni.setStorageSync('member', response.data.data && response.data.data.member && response.data.data.member);
				  uni.setStorageSync('keycode', response.data.data && response.data.data.auth);
				  this.$store.commit('setMember', response.data.data && response.data.data.member);
				  this.$store.commit('setMemberUid', response.data.data && response.data.data.member && response.data.data.member.uid);
				  this.$store.commit('setKeycode', response.data.data && response.data.data.auth);
				  
				  // 使用箭头函数保持this作用域
				  setTimeout(() => {
				      uni.showToast({
				          title: "登录成功",
				          icon: 'success',
				          duration: 1500
				      });
				      
				      // 确保在正确的作用域中执行
				      this.$emit('login-success'); // 触发登录成功事件
				      this.$emit('denglu_close_get'); // 关闭登录窗口
				      if (this.$refs.popup) {
				          this.$refs.popup.close();
				      }
				      
				      // 获取当前页面地址作为回调地址
				      let danqian_www = uni.getStorageSync('danqian_www');
				      
				      // 避免循环跳转，设置默认跳转地址
				      setTimeout(() => {
				          if (danqian_www && danqian_www !== window.location.href) {
				              window.location.href = danqian_www;
				          } else {
				              // 如果没有有效的回调地址或会导致循环跳转，则跳转到默认页面
				              //window.location.href = '/pages/wo/wo';
				          }
				      }, 1000);
				  }, 500);
				} else {
				  console.log('登录失败', response.data.msg || '未知错误');
				  // 登录失败后先显示提示
				  uni.showToast({
				      title: "登录失败: " + (response.data.msg || '未知错误'),
				      icon: 'none',
				      duration: 2000
				  });
				}
			}).catch(error => {
				console.error('登录请求异常', error);
				setTimeout(() => {
					uni.showToast({
						title: "网络异常，请重试",
						icon: 'none',
						duration: 2000
					});
				}, 500);
			});
		},
		//微信公众号登录接口
		weixingongzhonghao(){
			var duixin = this;
			//获取当前页面地址作为回调地址
			let local = encodeURIComponent(window.location.href);
			// 保存 local 到本地存储
			uni.setStorageSync('danqian_www', window.location.href);
			//微信公众号登录接口
			var wenxinurl = Api.postWeixingongzhonghaologin(local);
			//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
			window.location.href = wenxinurl;
			//console.log("到登录了login",location.href);
			
		},
		

	},
	computed: {
		// 统一处理高度样式，避免不同端对 rpx 的解析差异
		gaoduStyle() {
			const val = Number(this.gaodu) || 0;
			// #ifdef H5
			return { height: uni.upx2px(val) + 'px' };
			// #endif
			// #ifndef H5
			return { height: val + 'rpx' };
			// #endif
		}
	},
	watch: {
		denglu_xianshi_weibu(newVal, oldVal) {
			//console.log('kai')
			if(newVal == 1 || newVal == 1){
				this.$refs.popup.open();
			}
			
		}
		
	}
}
</script>

<style lang="scss">
	.denglu {
		width: 100%;
		/* 最大宽度 */
		
	    height: 100%;
	    z-index: 1000;
		left: 0;
	  top: 0;
	  position: fixed;
	  border-radius: 20rpx;
	  /*background-color: rgba(0, 0, 0, 0.5);*/ /* 半透明黑色背景 */
	  
	}
	
	.denglu_2 {
	  width: 100%;
	  /*最大宽度*/
	  max-width: 600rpx;
	  height: 900rpx;
	  position: fixed;
	  left: 50%;
	  top: 50%;
	  transform: translate(-50%, -50%);
	  background-color: rgba(255, 255, 255, 1); /* 半透明黑色背景 */
	  border-radius: 20rpx; /* 可选：添加圆角 */
	}
	.huise {
		background-color: #f5f5f5;
		height: 900rpx;
		border-radius: 0rpx 20rpx 20rpx 0 ; /* 可选：添加圆角 */
	}
	.d-erweima {
		width: 380rpx;
		height: 380rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		/* 左右居中 */
		margin-left: auto;
		margin-right: auto;
		/* 上下居中 */
		margin-top: auto;
		margin-bottom: auto;
		/* 居中 */
	}
	.title {
		padding-top: 30rpx;
		padding-bottom: 50rpx;
		view {
			padding-left: 64rpx;
			font-size: 48rpx;
			font-weight: 700;
			color: #383838;
		}
	}
	.form {
			flex: 1;
			padding: 0 64rpx;
	
			.tab {
				display: flex;
				align-items: center;
				justify-content: space-between;
				/*background-color: #ecf1fb;*/
				height: 100rpx;
				/*background: linear-gradient(180deg, #e3ebf9 0%, #ffffff 100%);*/
	
				view {
					width: 340rpx;
					line-height: 100rpx;
					text-align: center;
					color: #9e9e9e;
					position: relative;
				}
	
				view::after {
					content: '';
					width: 50rpx;
					height: 8rpx;
					display: block;
					background-color: #16afa8;
					border-radius: 4rpx;
					position: absolute;
					left: 50%;
					bottom: 14rpx;
					transform: translateX(-50%);
					opacity: 0;
				}
	
				view.select {
					background-color: #fff;
					color: #06adb3;
				}
	
				view.type1.select {
					border-radius: 0 40rpx 0 0;
				}
	
				view.type2.select {
					border-radius: 40rpx 0 0;
				}
	
				view.select::after {
					opacity: 1;
				}
			}
	
			.inputs {
				margin-bottom: 80rpx;
	
				>view {
					height: 96rpx;
					border-bottom: 1rpx solid #cdcdcd;
					display: flex;
					align-items: center;
	
					input {
						flex: 1;
					}
				}
	
				.account {
					margin-bottom: 48rpx;
	
					view {
						padding-right: 20rpx;
						margin-right: 20rpx;
						border-right: 1rpx solid #cdcdcd;
					}
				}
	
				.vcode {
					text {
						text-wrap: nowrap;
					}
				}
			}
	
			.button {
				view {
					line-height: 96rpx;
					border-radius: 20rpx;
					text-align: center;
					font-size: 32rpx;
					color: #ffffff;
					background-color: #16afa8;
				}
			}
	
			.tip {
				font-size: 28rpx;
				text-align: center;
				margin-top: 30rpx;
				color: #808080;
				/* 使用flex布局确保图标和文本居中 */
				display: flex;
				justify-content: center;
				align-items: center;
				height: 80rpx; /* 设置适当的高度 */
			}
		}
		.pact {
			display: flex;
			align-items: center;
			justify-content: center;
			padding-bottom: 70rpx;
			font-size: 24rpx;
	
			text {
				color: #3ba662;
			}
	
			radio {
				:deep(.uni-radio-input) {
					border: 1rpx solid #3ba662;
				}
	
				transform:scale(0.6)
			}
		}
		.d-xiala-0 {
		  position: relative;
		  display: inline-block;
		  
		  &:hover {
			  .d-xiala-1 {
			    display: block;
			  }
			}
		}
		.d-xiala-1 {
			/*margin: 30rpx;*/
		  position: absolute;
		  top: 100%;
		  left: 0;
		  background-color: #fff;
		  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		  border-radius: 8rpx;
		  padding: 5rpx 16rpx;
		  z-index: 1000;
		  min-width: 200rpx;
	      /*display: block;*/ /* 修改为block */
		  white-space: nowrap;
		
		 /* &.show {
		    display: block;
		  }*/
		}
		.d-denglu {
		  position: relative;
		}
		/* #ifdef APP || H5 */
		.d-kuan-baifen-70-cm {
			width: 100%;
		}
		/* #endif */
		/* #ifdef MP */
		.d-kuan-baifen-70-cm {
			width: 70%;
		}
		/* #endif */

</style>